package org.weed.gadgets.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.weed.gadgets.audio.asf.ASFConstants;

public class NioFileReader {
	private static final int BUFFER_SIZE = 1024;
	private FileChannel fileChannel;
	private ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
	private int availableData = 0;
	
	
	public NioFileReader(FileChannel fileChannel) {
		this.fileChannel = fileChannel;
	}
	
	public NioFileReader(File file) throws FileNotFoundException {
		this((new FileInputStream(file)).getChannel());
	}
	
	public NioFileReader(String path) throws FileNotFoundException {
		this(new File(path));
	}
	
	public long position() {
		try {
			return fileChannel.position();
		} catch (IOException e) {
			return -1;
		}
	}
	
	//======================================
	public byte[] read(int length) {
		ByteBuffer buffer = ByteBuffer.allocate(length);
		try {
			int byteRead;
			while (buffer.hasRemaining()) {
				byteRead = fileChannel.read(buffer);
				if (byteRead == -1) {
					System.err.println("EOF");
					return null;
				}
			}
			return buffer.array();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public byte[] read2(int length) {
		byte[] bytes = new byte[length];
		int byteToRead = length - availableData;
		try {
			if (byteToRead > 0) {
				for (int i=0; i<=length/BUFFER_SIZE; i++) {
					int byteRead = 0;
					int remaining = length - (i * BUFFER_SIZE);
					while (remaining > 0) {
						byteRead = fileChannel.read(buffer);
						if (byteRead == -1) {
							return null;
						}
						remaining = remaining - byteRead;
					}
					buffer.flip();
					byte[] buffer2 = buffer.array(); 
					ByteUtils.printBytes(buffer2);
					System.arraycopy(buffer2, 0, bytes, i*BUFFER_SIZE, buffer2.length);
					buffer.clear();
				}
			} else {
				
			}
			return bytes;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public byte[] read(long position, int length) {
		try {
			fileChannel.position(position);
			return read(length);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public byte[] reverseRead(int length) {
		byte[] bytes = read(length);
		ByteUtils.reverse(bytes);
		return bytes;
	}
	
	public byte[] reverseRead(long position, int length) {
		byte[] bytes = read(position, length);
		ByteUtils.reverse(bytes);
		return bytes;
	}
	
	public static void main(String[] args) throws Exception {
		FileChannel channel = new FileInputStream("C:\\Users\\ctang\\Desktop\\test.wma").getChannel();
		
		ByteBuffer buffer = ByteBuffer.allocate(8);
		while (buffer.remaining()>0) {
			buffer.put((byte)0xff);
		}
	}
}
